package com.unicloud.medical.aliyun.autoconfigure;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.unicloud.medical.aliyun.AliyunService;
import com.unicloud.medical.aliyun.starter.AliyunHealthCheckStarter;
import com.unicloud.medical.oss.common.beanFactoryPostProcessor.AbstractBeanFactoryPostProcessor;
import com.unicloud.medical.oss.common.constant.OSSTypeConstant;
import com.unicloud.medical.oss.common.model.OSSServerProperties;
import com.unicloud.medical.oss.common.util.CommonUtil;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ConfigurableApplicationContext;

public class AliyunBeanFactoryPostProcessor extends AbstractBeanFactoryPostProcessor {
    public AliyunBeanFactoryPostProcessor(ConfigurableApplicationContext applicationContext, String ossType) {
        super(applicationContext, ossType);
    }

    @Override
    protected String type() {
        return OSSTypeConstant.LANG_CHAO;
    }

    @Override
    protected void registerClient(OSSServerProperties ossServerProperties, BeanDefinitionRegistry registry) throws Exception {
        // ossClient
        OSS ossClient = new OSSClientBuilder().build(
                ossServerProperties.getEndpoint(),
                ossServerProperties.getAccessKey(),
                ossServerProperties.getSecretKey());
        String name = CommonUtil.buildName(ossServerProperties.getName(), OSSTypeConstant.ALIYUN, ossServerProperties.getEndpoint());

        // AliyunService
        registerBeanDefinition(registry, name + "AliyunService",
                BeanDefinitionBuilder
                        .genericBeanDefinition(AliyunService.class)
                        .addPropertyValue("name", name)
                        .addPropertyValue("aliyunProperties", ossServerProperties)
                        .addPropertyValue("ossClient", ossClient)
                        .getBeanDefinition());

        // AliyunHealthCheckStarter
        registerBeanDefinition(registry, name + "AliyunHealthCheckStarter",
                BeanDefinitionBuilder
                        .genericBeanDefinition(AliyunHealthCheckStarter.class)
                        .addPropertyValue("ossClient", ossClient)
                        .addPropertyValue("check", ossServerProperties.getCheck())
                        .getBeanDefinition());
    }

}
